#!/bin/bash

echo "========================================"
echo "启动项目管理系统（前端+后端）"
echo "========================================"
echo

# 获取脚本所在目录的父目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

cd "$PROJECT_DIR"

echo "检查运行环境..."
echo

echo "检查Java环境..."
if ! command -v java &> /dev/null; then
    echo "错误：未找到Java环境，请确保已安装JDK 8或更高版本"
    exit 1
fi

echo "检查Node.js环境..."
if ! command -v node &> /dev/null; then
    echo "错误：未找到Node.js环境，请确保已安装Node.js 16或更高版本"
    exit 1
fi

echo "检查Maven环境..."
if ! command -v mvn &> /dev/null; then
    echo "错误：未找到Maven环境，请确保已安装Maven 3.6或更高版本"
    exit 1
fi

echo "环境检查完成！"
echo

# 创建日志目录
mkdir -p logs

echo "启动后端服务..."
gnome-terminal --title="后端服务" -- bash -c "cd '$SCRIPT_DIR' && ./start-backend.sh; exec bash" 2>/dev/null || \
xterm -title "后端服务" -e "cd '$SCRIPT_DIR' && ./start-backend.sh; bash" 2>/dev/null || \
open -a Terminal "$SCRIPT_DIR/start-backend.sh" 2>/dev/null || \
echo "无法打开新终端窗口，请手动运行 ./scripts/start-backend.sh"

echo "等待后端服务启动..."
sleep 10

echo "启动前端服务..."
gnome-terminal --title="前端服务" -- bash -c "cd '$SCRIPT_DIR' && ./start-frontend.sh; exec bash" 2>/dev/null || \
xterm -title "前端服务" -e "cd '$SCRIPT_DIR' && ./start-frontend.sh; bash" 2>/dev/null || \
open -a Terminal "$SCRIPT_DIR/start-frontend.sh" 2>/dev/null || \
echo "无法打开新终端窗口，请手动运行 ./scripts/start-frontend.sh"

echo
echo "========================================"
echo "服务启动完成！"
echo "========================================"
echo "后端服务：http://localhost:8080"
echo "前端服务：http://localhost:5173"
echo
echo "请等待服务完全启动后访问前端地址"
echo "关闭此窗口不会停止服务，请在各自的窗口中按Ctrl+C停止"
echo "========================================"
echo